package org.projects.graduates.domain;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import com.dayatang.domain.AbstractEntity;
import com.dayatang.domain.QuerySettings;

@Entity
@Table(name = "user_roles")
public class UserRoles extends AbstractEntity {
	private static final long serialVersionUID = -8252921528867771116L;

	@OneToOne
	private User user;
	@OneToOne
	private Role role;

	public static Set<Role> findRolesOf(User user) {
		Set<Role> results = new HashSet<Role>();
		QuerySettings<UserRoles> settings = QuerySettings.create(UserRoles.class);
		settings.eq("user", user);
		for (UserRoles ur : getRepository().find(settings)) {
			results.add(ur.getRole());
		}
		return results;
	}

	public static Set<String> findRoleNamesOf(User user) {
		Set<String> results = new HashSet<String>();
		for (Role role : findRolesOf(user)) {
			results.add(role.getName());
		}
		return results;
	}

	public int hashCode() {
		return getUser().getUsername().hashCode() + getRole().getName().hashCode();
	}

	@Override
	public boolean equals(Object other) {
		if (other instanceof UserRoles) {
			UserRoles otherUR = (UserRoles) other;
			boolean userIdFlag = otherUR.getUser().getId().equals(this.getUser().getId());
			boolean roleNameFlag = otherUR.getRole().getName().equals(this.getRole().getName());
			return (userIdFlag && roleNameFlag);
		}
		return false;
	}

	public String toString() {
		return "UserRoles " + this.getUser() + this.getRole();
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

}
